#!/bin/sh

# .........................................................................
# the CHARMM scripts to convert a set of frames to a DCD file and
# to pull out a set of coordinates from the DCD file 
# .........................................................................

# Assign start values to variables 
probe="CMTS"
crdroot="build"
psfroot="build"
dcdroot="mmcm"
frameout="frames"
first=1
skip=1
        
# determine how many frames there are
	numframes=`awk 'END{print(NR-3)}' $dcdroot.ene`
	echo number of frames $numframes


# segment ID, residue ID and number
	awk '/CMTS/ && /SG/ {print $8 " " $9 " " $2}' build.crd > label.txt
	labelsegid=`awk 'NR==1 {print $1}' label.txt`
	labelresid=`awk 'NR==1 {print $2}' label.txt`
	labelresno=`awk 'NR==1 {print $3}' label.txt`

	echo label residue ID $labelresid "  " segment $labelsegid " " ResNO $labelresno;

# compile the frames into DCD file
	charmm < $SL_MOD/charmm/charmm_inp/frames2dcd.inp numframes="$numframes" > frames2dcd.out

# retrieve the coordinates of nitroxides
	charmm < $SL_MOD/charmm/charmm_inp/getccno_$probe.inp numframes="$numframes" \
		labresid="$labelresid" labsegid="$labelsegid" site="$labelresno" \
		probe="$probe" protein="$protein" crdroot="$crdroot" psfroot="$psfroot" \
		dcdroot="$dcdroot" frameout="$frameout" firsttime="$first" lasttime="$numframes" skiptime="$skip" \
		> getccno.out  
        
	awk 'NR>16 {print $2,$3,$4,$5,$6,$7,$8,$9,$10}' ccnoa.dat > ccnoa1.data
	awk 'NR>16 {print $2,$3,$4,$5,$6,$7,$8,$9,$10}' ccnob.dat > ccnob1.data
	awk 'NR>16 {print $2,$3,$4}' ccnoc.dat > ccnoc1.data
	awk 'NR>2 {print $0}' mmcm.ene> mmcm.en1

# checking how many records they are in the files        
	rec_1=`awk 'END {print(NR)}' mmcm.en1`
	rec_2=`awk 'END {print(NR)}' ccnob1.data`
	echo records in mmcm.ene file: $rec_1
	echo records in ccnob1.data file: $rec_2
	if [ $rec_1 -lt $rec_2 ]; then 
	rec=$rec_1
	else 
	rec=$rec_2
	fi
	echo common records: $rec
# create an ASCII file with the energies and coordinates of nitroxide
	paste mmcm.en1 ccnoa1.data ccnob1.data ccnoc1.data > mmcm.swp
  	awk 'NR < '$rec'+1 {print $0}' mmcm.swp > mmcm.dat
	
# create a file of frame numbers sorted according to the lowest energy
        cat -n mmcm.dat | sort -n -k2 > mmcm_Vsorted.dat

        framenum=`awk 'NR==1 {print $1}' mmcm_Vsorted.dat`
	numframes=$(($framenum+1));
	echo best frame $framenum
	echo read frames $numframes
# retrieve the best frame and store in a pdb and crd format
	charmm < $SL_MOD/charmm/charmm_inp/getframe.inp framenum="$framenum" numframes="$numframes" > getframe.out 
	infile="frame$framenum.pdb";
	echo $infile
rm *.swp 
rm *.data
rm mmcm.en1
rm ccno?.dat
rm ccno??.dat
